package xmlStateMachine.commands {

	import de.ghost23.common.process.ACommand;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import xmlStateMachine.XMLStateMachine;

	public class RequestFile extends ACommand {

		private var xmlLoader:URLLoader;
		private var data:Dictionary;

		public function RequestFile() {
			super();
		}

		/**
		 * Starts execution of this Command. This method has to be overridden
		 * by the subclass.
		 * @param	paramContainer Reference to the bundling Parameter Container.
		 */
		override public function execute(paramContainer:Dictionary):void {

			trace("command RequestFile is running with file: " + paramContainer[XMLStateMachine.FILE_URL]);
			data = paramContainer;

			if(data[XMLStateMachine.FILE_URL] == null) setResult(FAILURE);
			else {

				xmlLoader = new URLLoader();
				xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
				xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
				xmlLoader.load(new URLRequest(data[XMLStateMachine.FILE_URL]));
			}
		}

		private function onLoadError(event:IOErrorEvent):void {

			xmlLoader.removeEventListener(Event.COMPLETE, onLoadComplete);
			xmlLoader = null;
			data = null;
			setResult(XMLStateMachine.FILE_LOAD_FAILED);
		}

		private function onLoadComplete(event:Event):void {

			data[XMLStateMachine.FILE_RAW_XML] = xmlLoader;
			xmlLoader.removeEventListener(Event.COMPLETE, onLoadComplete);
			xmlLoader = null;
			data = null;
			setResult(XMLStateMachine.FILE_LOAD_COMPLETE);
		}
	}
}